package com.ruoyi.yf.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.yf.domain.YfTag;
import com.ruoyi.yf.domain.mobile.*;
import com.ruoyi.yf.mapper.ReportMapper;
import com.ruoyi.yf.mapper.YfTagMapper;
import com.ruoyi.yf.service.IYfTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 条形码Service业务层处理
 *
 * @author XiaoYi...
 * @date 2020-03-17
 */
@Service("yfTagService")
public class YfTagServiceImpl implements IYfTagService {

    @Autowired
    private YfTagMapper yfTagMapper;

    @Autowired
    private ReportMapper reportMapper;

    /**
     * 查询条形码
     *
     * @param codeid 条形码ID
     * @return 条形码
     */
    @Override
    public YfTag selectYfTagById(String codeid) {
        return yfTagMapper.selectYfTagById(codeid);
    }

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询条形码列表
     *
     * @param yfTag 条形码
     * @return 条形码
     */
    @Override
    public List<YfTag> selectYfTagList(YfTag yfTag) {
        //ShiroUtils.getSysUser().getRoles().get(0).getRoleKey().equals("user_c_manager")
        return yfTagMapper.selectYfTagList(yfTag);
    }

    /**
     * 查询条形码列表,处置公司所负责的医院的数据
     *
     * @param yfTag 条形码
     * @return 条形码
     */
    @Override
    public List<YfTag> selectDisposalCompanyYfTagList(YfTag yfTag, Long deptId) {
        //查询处置公司下的医院id
        List<Long> ids = deptMapper.selectHospitalByComponyId(deptId);
        List<YfTag> yfTags = yfTagMapper.selectYfTagList(yfTag);
        //判断tag是的医院id是否在ids集合中，如果不在就从集合中删除
        for (int i = yfTags.size() - 1; i >= 0; i--) {
            if(!ids.contains(yfTags.get(i).getHospitalId())){
                yfTags.remove(i);
            }
        }
        return yfTags;
    }


    /**
     * 新增条形码
     *
     * @param yfTag 条形码
     * @return 结果
     */
    @Override
    public int insertYfTag(YfTag yfTag) {
        yfTag.setCreateTime(DateUtils.getNowDate());
        return yfTagMapper.insertYfTag(yfTag);
    }

    /**
     * 修改条形码
     *
     * @param yfTag 条形码
     * @return 结果
     */
    @Override
    public int updateYfTag(YfTag yfTag) {
        yfTag.setUpdateTime(DateUtils.getNowDate());
        return yfTagMapper.updateYfTag(yfTag);
    }

    /**
     * 删除条形码对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteYfTagByIds(String ids) {
        return yfTagMapper.deleteYfTagByIds(Convert.toStrArray(ids));
    }

    /**
     * 批量标记删除
     *
     * @param ids
     * @return
     */
    @Override
    public int updateRremoveAndRecoveryTagByIds(String ids, String status) {
        return yfTagMapper.updateRremoveAndRecoveryTagByIds(Convert.toStrArray(ids), status);
    }

    /**
     * 删除条形码信息
     *
     * @param codeid 条形码ID
     * @return 结果
     */
    @Override
    public int deleteYfTagById(String codeid) {
        return yfTagMapper.deleteYfTagById(codeid);
    }

    /**
     * XiaoYi...
     * 查询条形码 关联医院查询 唯一
     *
     * @param yfTag
     * @Date : 2020-03-17 18:02
     */
    @Override
    public List<YfTag> selectYfTagListOnly(YfTag yfTag) {
        return yfTagMapper.selectYfTagListOnly(yfTag);
    }


//    public Map<String, TreeMap<String, Object>> report_01(Long hospitalid) {
//
//        List<Report> reports = yfTagMapper.report_01(hospitalid);
//
//        Map<String, TreeMap<String, Object>> map = new HashMap<>();
//
//
//        for (Report report : reports) {
//            TreeMap<String, Object> li = map.get(report.getId());
//            if (li == null)
//                li = new TreeMap<>();
//
//            if (report.getCodeId().equals("1")) {//病理性
//                li.put("bl_w", report == null ? 0.00 : report.getWeight());
//                li.put("bl_C", report == null ? 0 : report.getCount());
//            } else if (report.getCodeId().equals("2")) {//损伤性
//                li.put("ssx_w", report == null ? 0.00 : report.getWeight());
//                li.put("ssx_C", report == null ? 0 : report.getCount());
//            } else if (report.getCodeId().equals("3")) {//感染性
//                li.put("grx_w", report == null ? 0.00 : report.getWeight());
//                li.put("grx_C", report == null ? 0 : report.getCount());
//            } else if (report.getCodeId().equals("4")) {//药物性
//                li.put("yw_w", report == null ? 0.00 : report.getWeight());
//                li.put("yw_C", report == null ? 0 : report.getCount());
//            } else if (report.getCodeId().equals("5")) {//化学性
//                li.put("hxx_w", report == null ? 0.00 : report.getWeight());
//                li.put("hxx_C", report == null ? 0 : report.getCount());
//            } else if (report.getCodeId().equals("6")) {//胎盘
//                li.put("tp_w", report == null ? 0.00 : report.getWeight());
//                li.put("tp_C", report == null ? 0 : report.getCount());
//            }
//            li.put("name", report == null ? null : report.getName());
//
//
//            map.put(report.getId(), li);
//        }
//
//        //通过构造方法创建writer
//        //ExcelWriter writer = new ExcelWriter("d:/writeTest.xls");
//
//        List<List<Object>> rows = new ArrayList<>();
//
//        for (String key : map.keySet()) {
//            TreeMap<String, Object> treeMap = map.get(key);
//            List<Object> row = CollUtil.newArrayList(treeMap.get("name"),
//                    treeMap.get("grx_w"), treeMap.get("grx_C"),
//                    treeMap.get("ssx_w"), treeMap.get("ssx_C"),
//                    treeMap.get("bl_w"), treeMap.get("bl_C"),
//                    treeMap.get("yw_w"), treeMap.get("yw_C"),
//                    treeMap.get("hxx_w"), treeMap.get("hxx_C"));
//            rows.add(row);
//        }
//        System.out.println(rows);
//
//
//
//
//        //初始化配置
//        ExcelWriter writer = GenerateReport.Initialize();
//
//        //设置样式、字体
//        //添加行
////        Font font = writer.createFont();
////        StyleSet style = writer.getStyleSet();
////        style.setBorder(BorderStyle.THIN, IndexedColors.BLACK);
//
//        writer.passRows(4);
//        writer.write(rows);//.setStyleSet(style).getStyleSet().setFont(font, false);
//
//        writer.close();
//
//
//        return map;
//    }


    /**
     * 查询当前入库数据
     *
     * @param uid
     * @return
     */
    @Override
    public List<YfTag> selectInpSM(Long uid) {
        return yfTagMapper.selectSMS("20", uid);
    }


    /**
     * 查询未出库完成的医废列表
     */
    @Override
    public List<YfTag> getNoOutStoreCompleteYF(Long sid,Long ksid) {
        return yfTagMapper.getNoOutStoreCompleteYF(sid,ksid);
    }

    /**
     * 查询当前出库数据
     *
     * @param uid
     * @return
     */
    @Override
    public List<YfTag> selectOutSM(Long uid) {
        return yfTagMapper.selectSMS("30", uid);
    }


    /**
     * 批量添加医废
     * 使用事务
     *
     * @param tags
     * @return
     */
    @Override
    @Transactional
    public int insertYfTagList(List<YfTag> tags) {
        int i = -1;
        for (YfTag yfTag : tags) {
            i = yfTagMapper.insertYfTag(yfTag);
            if (i < 0) {
                return -1;
            }
        }
        return 1;
    }

    // 批量添加医废
    @Override
    public int insertBatchYfTagList(List<YfTag> list) {
        return yfTagMapper.insertBatchYfTagList(list);
    }


    /**
     * 批量出库
     *
     * @param ids
     * @return
     */
    @Override
    public int updateSMS(Long uid, String[] ids) {
        //status ：3 = 出库；
        return yfTagMapper.updateSMS(uid, "30", ids);
    }


    /**
     * 根据暂存点id、uid查询最后一次入库日期
     *
     */
    @Override
    public Date getLastInputTimeBySidAndUid(String sid, String uid) {
        return yfTagMapper.getLastInputTimeBySidAndUid(sid, uid);
    }

    /**
     * 根据暂存点id、uid查询最后一次出库日期
     *
     */
    @Override
    public Date getLastOutTimeBySidAndUid(String sid, String uid) {
        return yfTagMapper.getLastOutTimeBySidAndUid(sid, uid);
    }

    /**
     * 根据暂存点id、uid查询当前库存
     *
     */
    @Override
    public Double getCurrentInventoryBySidAndUid(String sid, String uid) {
        return yfTagMapper.getCurrentInventoryBySidAndUid(sid, uid);
    }

    /**
     * 根据暂存点id查询暂存预警值
     *
     */
    @Override
    public List<YfLStoreValue> getStoreValueBySid(String sid) {
        return yfTagMapper.getStoreValueBySid(sid);
    }


    /**
     * 医废类型日统计查询
     *
     * @param uid
     * @param date
     * @return
     */
    @Override
    public List<YfTypeStatis> selectUnionAll(String uid, String date) {
        return yfTagMapper.selectUnionAll(uid, date);
    }


    /**
     * 查询今天各医废状态袋数
     *
     * @param uid
     * @return
     */
    @Override
    public String getTodayYFNum(Long uid) {
        return yfTagMapper.getTodayYFNum(uid);
    }


    /**
     * 上传医废照片
     *
     * @param codeId
     * @param imgPath
     */
    @Override
    public void saveIMG(String codeId, String imgPath, String yfStatusFlag) {
        yfTagMapper.saveIMG(codeId, imgPath, yfStatusFlag);
    }


    /**
     * 根据暂存点id去视图查询医院id
     *
     * @param stagingId
     * @return
     */
    @Override
    public SysDept getHospitalByStaging(Long stagingId) {
        return yfTagMapper.getHospitalByStaging(stagingId);
    }


    /**
     * 根据条码获取医废信息，联查各状态人员姓名
     */
    @Override
    public YfTag getYFInfoByBarcode(String codeId) {
        return yfTagMapper.getYFInfoByBarcode(codeId);
    }


    /**
     * 根据条码和暂存点获取医废信息，联查各状态人员姓名
     */
    @Override
    public YfTag getYFInfoByBarcodeAndStagingId(String codeId, Long stagingId) {
        return yfTagMapper.getYFInfoByBarcodeAndStagingId(codeId, stagingId);
    }


    /**
     * 根据暂存点id查询已收集医废(按收集员姓名分组)
     */
    @Override
    public List<YfUserBag> getAlreadyCollYFByDeptId(Long stagingId) {
        return yfTagMapper.getAlreadyCollYFByDeptId(stagingId);
    }

    /**
     * 根据暂存点id查询已转运医废(按转运员姓名分组)
     */
    @Override
    public List<YfUserBag> getAlreadyTransYFByDeptId(Long stagingId) {
        return yfTagMapper.getAlreadyTransYFByDeptId(stagingId);
    }

    /**
     * 根据暂存点id查询已入库医废(按入库员姓名分组)
     */
    @Override
    public List<YfUserBag> getAlreadyInStoreYFByDeptId(Long stagingId) {
        return yfTagMapper.getAlreadyInStoreYFByDeptId(stagingId);
    }


    /**
     * 根据暂存点、收集人、医废状态查询医废
     */
    @Override
    public List<YfTag> getStatusYF(Long stagingId, Long userId, String yfStatus, Long workId) {
        return yfTagMapper.getStatusYF(stagingId, userId, yfStatus, workId);
    }


    /**
     * 收集 -> 转运 医废
     */
    @Override
    public void collToTransYF(String codeId, Long userId) {
        yfTagMapper.collToTransYF(codeId, userId);
    }

    /**
     * 收集 -> 入库 医废
     */
    @Override
    public void collToInStoreYF(String codeId, Long userId) {
        yfTagMapper.collToInStoreYF(codeId, userId);
    }

    /**
     * 转运 -> 入库 医废
     */
    @Override
    public void transToInStoreYF(String codeId, Long userId) {
        yfTagMapper.transToInStoreYF(codeId, userId);
    }

    /**
     * 入库 -> 出库 医废
     */
    @Override
    public void inStoreToOutStoreYF(String codeId, Long userId) {
        yfTagMapper.inStoreToOutStoreYF(codeId, userId);
    }

    /**
     *  一键入库 收集 -> 入库
     */
    @Override
    public void oneKeyCollToInStoreYF(Long stagingId, Long userId){
        yfTagMapper.oneKeyCollToInStoreYF(stagingId,userId);
    }

    /**
     *  一键入库 转运 -> 入库
     */
    @Override
    public void oneKeyTransToInStoreYF(Long stagingId, Long userId){
        yfTagMapper.oneKeyTransToInStoreYF(stagingId,userId);
    }

    /**
     *  一键出库 入库 -> 出库
     */
    @Override
    public void oneKeyOutStoreYF(Long stagingId, Long userId) {
        yfTagMapper.oneKeyOutStoreYF(stagingId,userId);
    }


    /**
     * 根据采集人查询当日各科室各类型医废重量及袋数
     */
    @Override
    public List<YfTag> getTodayEachKSYFWeightAndNumByUserId(Long stagingId, Long userId, Date date) {
        return yfTagMapper.getTodayEachKSYFWeightAndNumByUserId(stagingId, userId, date);
    }


    /**
     * 根据采集人查询当日各科室各类型医废重量及袋数
     */
    @Override
    public List<YfHospitalMonth> getMonthKSYFWeightAndNumByUserId(Long stagingId, Long userId, String date) {
        return yfTagMapper.getMonthKSYFWeightAndNumByUserId(stagingId, userId, date);
    }


    /**
     * 按条件查询医废历史记录
     */
    @Override
    public List<YfTag> getYFRecordByCondition(Integer pageNo, Integer pageSize, Long userId, Long stagingId,
                                              String yftype, String startDate, String endDate) {
        int indexLength = Integer.valueOf(pageSize);
        int startIndex = (Integer.valueOf(pageNo) - 1) * indexLength;
        return yfTagMapper.getYFRecordByCondition(userId, stagingId, yftype, startDate, endDate, startIndex, indexLength);
    }

    /**
     * 获取医院医废统计报表
     */
    @Override
    public List<YfTag> getYFSatisticalByHospitalId(Long userId, Long hospitalId, String startDate, String endDate) {
        if( userId == null || hospitalId == null || StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) ){
            return new ArrayList<>();
        }else{
            return yfTagMapper.getYFSatisticalByHospitalId(userId, hospitalId, startDate, endDate);
        }
    }


    // 批量添加医废（用于数据迁移）
    @Override
    public void saveYfTagList(List<YfTag> yfTagList) {
        yfTagMapper.saveYfTagList(yfTagList);
    }

    //  查询旧平台医废
    @Override
    public List<OldYF> getOldYF(int startIndex, int yfLength) {
        return yfTagMapper.getOldYF(startIndex, yfLength);
    }

    // 查询旧平台照片
    @Override
    public List<OldPhoto> getAllOldPhoto() {
        return yfTagMapper.getAllOldPhoto();
    }


    // 查询旧平台医废总数
    @Override
    public int getAllOldYFNum() {
        return yfTagMapper.getAllOldYFNum();
    }


    // 保存部分出库医废list
    @Override
    public int savePartOutStoreYF(List<YfTag> zyfList) {
        return yfTagMapper.savePartOutStoreYF(zyfList);
    }

    // 大批量添加测试数据到数据库
    @Override
    public void insertYFBatchData(List<YfTag> list) {
        yfTagMapper.insertYFBatchData(list);
    }

    // 接口 - 批量添加医废
    @Override
    public void insertInterfaceYfTagList(List<YfTag> list) {
        yfTagMapper.insertInterfaceYfTagList(list);
    }

    // 接口 - 批量更新医废
    @Override
    public void updateInterfaceYfTagList(List<YfTag> list) {
        yfTagMapper.updateInterfaceYfTagList(list);
    }


    // 查询石家庄卫健委下属的所有暂存点未提交的医废数据
    @Override
    public List<YfTag> getNoSubmitYF(Long deptId) {
        return yfTagMapper.getNoSubmitYF(deptId);
    }

    // 根据提交的条码和状态更改update_status
    @Override
    public void updateStatusYFBycodeidAndStatus(List<YfTag> list) {
        yfTagMapper.updateStatusYFBycodeidAndStatus(list);
    }

    // 先根据id批量删除医废，再批量添加医废
    @Override
    @Transactional
    public void receiveYFData(List<YfTag> list) {
        // 批量删除
        String [] codeids = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            codeids[i] = list.get(i).getCodeid();
        }
        yfTagMapper.deleteYFBycodeid(codeids);
        // 批量添加
        yfTagMapper.insertDelYfTagList(list);
    }


    // 查询石家庄卫健委下所有的暂存点，更改暂存点填报时间
    @Override
    public List<Long> getStagingIdsBySJZWJWID(Long sjzwjwid) {
        return yfTagMapper.getStagingIdsBySJZWJWID(sjzwjwid);
    }

    // 石家庄卫健委服务器接收今日无医废暂存点ids
    @Override
    public void receiveNoYFStagingIds(List<Long> staginglist) {
        Long [] stagingids = new Long[staginglist.size()];
        for (int i = 0; i < staginglist.size(); i++) {
            stagingids[i] = staginglist.get(i);
        }
        yfTagMapper.receiveNoYFStagingIds(stagingids);
    }



    // 根据暂存点id或医院id查询医废(按科室分组)
    @Override
    public List<YfVehicle> getStatusYFByDeptIdGroupByKS(Long stagingId, Long hospitalId, String yfStatus) {
        return yfTagMapper.getStatusYFByDeptIdGroupByKS(stagingId, hospitalId, yfStatus);
    }

    // 根据科室id及医废状态查询未入库医废总袋数及重量
    @Override
    public YfVehicle getYFTotalByKsIdAndYFStatus(Long stagingId, Long ksId, String yfStatus){
        return yfTagMapper.getYFTotalByKsIdAndYFStatus(stagingId, ksId, yfStatus);
    }

    // 只有指定科室已收集状态才能修改成已入库状态
    @Override
    public void oneKSCollToInStoreYF(Long stagingId, Long ksId, Long userId) {
        yfTagMapper.oneKSCollToInStoreYF(stagingId, ksId, userId);
    }

    // 只有指定科室已入库状态才能修改成已出库状态
    @Override
    public void oneKSInToOutStoreYF(Long stagingId, Long ksId, Long userId) {
        yfTagMapper.oneKSInToOutStoreYF(stagingId, ksId, userId);
    }

    // 根据科室id及医废状态查询医废
    @Override
    public List<YfVehicle> getStatusYFByKSId(Long stagingId, Long ksId, String yfStatus) {
        return yfTagMapper.getStatusYFByKSId(stagingId, ksId, yfStatus);
    }

    // 根据医废状态、用户等查询当天医废汇总
    @Override
    public List<YfTypeStatis> getDayYFStatusStatis(Long userId, Long stagingId, Long hospitalId, String yfStatus, String day) {
        return yfTagMapper.getDayYFStatusStatis(userId, stagingId, hospitalId, yfStatus, day);
    }

    // 查询已入库的医废列表
    @Override
    public List<YfTag> getInStoreYFlistByStagingId(Long stagingId, Long ksId) {
        return yfTagMapper.getInStoreYFlistByStagingId(stagingId, ksId);
    }

    // 选择出库 - 医废出库
    @Override
    public int saveOutStoreYFlist(List<YfTag> yfList, Long userId) {
        return yfTagMapper.saveOutStoreYFlist(yfList, userId);
    }


    // 查询扫码科室今天的医废列表
    @Override
    public List<YfTag> getDepartmentTodayYFTypeList(Long stagingId, Long ksId, Long userId) {
        return yfTagMapper.getDepartmentTodayYFTypeList(stagingId, ksId, userId);
    }

    // 查询当前用户今天收集科室的医废列表
    @Override
    public List<YfTag> getAllKSTodagYFListByUserId(Long stagingId, Long userId) {
        return yfTagMapper.getAllKSTodagYFListByUserId(stagingId, userId);
    }

    // 保存医废收集页面第二张照片
    @Override
    public void saveCollPhoto2(String codeId, String imgPath) {
        yfTagMapper.saveCollPhoto2(codeId, imgPath);
    }



}
